package com.dinglian.ots.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.dinglian.ots.common.EncryptHelper;
import com.dinglian.ots.common.model.Constant;
import com.dinglian.ots.common.model.RequestHelper;
import com.dinglian.ots.exception.GlobalException;
import com.dinglian.ots.redis.CodeKey;
import com.dinglian.ots.redis.RedisService;
import com.dinglian.ots.redis.TokenMapKey;
import com.dinglian.ots.redis.UserKey;
import com.dinglian.ots.result.CodeMsg;
import com.dinglian.ots.vo.user.UserVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class RequestInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map responseMap = new HashMap<>();
        try {

            String path=request.getRequestURI();
            if(path.indexOf("/export")>-1){
                /*Session session = SecurityUtils.getSubject().getSession();
                UserVo userVo = (UserVo) session.getAttribute(Constant.SESSION_USER);
                System.out.println("导出选款单session的值"+userVo);
                if (userVo == null){
                    throw new GlobalException(CodeMsg.USER_NOT_LOGIN);
                }*/
                return  true;
            }else{
                // 1.从请求头获取session-token
                String sessionToken = request.getHeader(RequestHelper.HEADER_TOKEN);
                System.out.println("session-token"+sessionToken);
                if (StrUtil.isBlank(sessionToken)) {
                    throw new GlobalException(CodeMsg.INVALID_SESSION_TOKEN);
                }
                // 2.根据token获取用户信息
                UserVo user = redisService.get(UserKey.getKey, sessionToken, UserVo.class);
                if (user == null) {
                    throw new GlobalException(CodeMsg.USER_NOT_LOGIN);
                }

                redisService.set(UserKey.getKey, sessionToken, user);
               /* // 3.校验token是否唯一
                String userMapToken = redisService.get(TokenMapKey.getKey, EncryptHelper.SHA1(user.getUsername()), String.class);
                System.out.println("userMapToken"+userMapToken);
                if (!sessionToken.equals(userMapToken)) {
                    throw new GlobalException(CodeMsg.INVALID_SESSION_TOKEN);
                }*/
                Session session = SecurityUtils.getSubject().getSession();
                session.setAttribute(Constant.SESSION_USER,user);
            }



            return true;
        } catch (GlobalException e) {
            response.setContentType(RequestHelper.CONTENT_TYPE_TEXT);
            response.setCharacterEncoding(RequestHelper.CHARACTER_ENCODING);
            response.getWriter().write(JSONObject.toJSONString(e.getCm()));
        } catch (Exception e) {
            response.setContentType(RequestHelper.CONTENT_TYPE_TEXT);
            response.setCharacterEncoding(RequestHelper.CHARACTER_ENCODING);
            response.getWriter().write(JSONObject.toJSONString(CodeMsg.SERVER_ERROR));
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
